package freemind.controller;

import freemind.controller.AtributoEnegModulo;
import freemind.main.XMLElement;
import freemind.main.XMLParseException;

import java.util.ArrayList;


public class XMLMindMapRemoveProtocol extends XMLProtocolBase implements XMLProtocol {
	
	XMLElement no;
	
	XMLElement request;
	XMLElement response;
	
	ArrayList<AtributoEnegModulo> extras;
	
	public XMLMindMapRemoveProtocol(int eneg_modulo) {
		super(XMLProtocol.REMOVE,eneg_modulo);
		
		no = new XMLElement();
		no.setName("no");
		
		extras = new ArrayList<AtributoEnegModulo>();
	}
	
	public void addAtribute(AtributoEnegModulo attr){
		extras.add(attr);
	}
	
	public void makeRequest(NodeAdapterBase adapter){
		super.makeRequest();
		
		request = super.getXML(adapter);
		
			XMLElement nodeIdElement = new XMLElement();
			nodeIdElement.setName("node_id");
			nodeIdElement.setContent( String.valueOf(adapter.getId()) );
		
		request.addChild( nodeIdElement );
		
		XMLElement extrasElement = new XMLElement();
		extrasElement.setName("extras");
		
		for(AtributoEnegModulo attr:extras){
			XMLElement el = new XMLElement();
			el.setName(attr.getNome());
			el.setContent(attr.getValor());
			
			for(AtributoEnegModulo child:attr.getChildren()){
				el= addChildElement( el, child );
			}
			
						
			extrasElement.addChild(el);
		}
		
		request.addChild(extrasElement);
	}
	
	private XMLElement addChildElement(XMLElement parent,AtributoEnegModulo attr){
	
		XMLElement extraElement = new XMLElement();
		extraElement.setName(attr.getNome());
		extraElement.setContent(attr.getValor());
		
		for(AtributoEnegModulo child:attr.getChildren()){
			extraElement = addChildElement( extraElement, child );
		}		
		
		parent.addChild( extraElement );
		
		return parent;
		
		
	}
	
	public XMLMindMapRemoveProtocol getResponse(NodeAdapterBase adapter){
		super.getResponse();
		response = super.getXML(adapter);
		
		
		return this;
	}
	
	public int getNodeId(){
		XMLElement nodeIdElement = (XMLElement) request.getChildren().get(1);
		return Integer.parseInt( nodeIdElement.getContent() );		
	}
	
	public XMLElement getExtra(){
		XMLElement extras = (XMLElement) request.getChildren().get(2);
		return extras;
	}
	
	public XMLElement getXML(){
		if( this.getOperacao() == XMLProtocol.REQUEST ){
//			System.out.println("REQUEST REMOVE: " + request.toString());
			return request;
		}
		else if( this.getOperacao() == XMLProtocol.RESPONSE ){
//			System.out.println("RESPONSE REMOVE: " + response.toString());
			return response;
		}
		
		return null;
	}
	
	public XMLElement readXML(String s ) throws XMLParseException{
		XMLElement newElement = super.readXML(s);
		
		if( this.getOperacao()==XMLProtocol.REQUEST ){
			this.request = newElement;
		}
		else if( this.getOperacao() == XMLProtocol.RESPONSE ){
			this.response = newElement;
		}				
		
		return newElement;
	}			

}

